package com.heihx.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.heihx.constant.MessageConstant;
import com.heihx.constant.StatusConstant;
import com.heihx.dto.SetmealDTO;
import com.heihx.dto.SetmealPageQueryDTO;
import com.heihx.entity.Dish;
import com.heihx.entity.Setmeal;
import com.heihx.entity.SetmealDish;
import com.heihx.exception.DeletionNotAllowedException;
import com.heihx.exception.SetmealEnableFailedException;
import com.heihx.mapper.SetMealMapper;
import com.heihx.result.PageResult;
import com.heihx.service.SetMealDishService;
import com.heihx.service.SetMealService;
import com.heihx.vo.DishItemVO;
import com.heihx.vo.SetmealVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, Setmeal> implements SetMealService {
    @Autowired
    private SetMealMapper setMealMapper;

    @Autowired
    private SetMealDishService setMealDishService;

    /**
     * 新增套餐并保存套餐和菜品的关联
     * @param setmealDTO
     */
    @Override
    @GlobalTransactional
    public void saveWithDish(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);
        //向套餐表插入数据
        setMealMapper.insert(setmeal);
        Long id = setmeal.getId();

        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(id);
        });

        //插入数据到关联表
        setMealDishService.saveBatch(setmealDishes);
    }

    /**
     * 分页查询套餐
     * @param setmealPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(SetmealPageQueryDTO setmealPageQueryDTO) {
        Page<Setmeal> page = Page.of(setmealPageQueryDTO.getPage(), setmealPageQueryDTO.getPageSize());

        Integer categoryId = setmealPageQueryDTO.getCategoryId();
        String name = setmealPageQueryDTO.getName();
        Integer status = setmealPageQueryDTO.getStatus();

        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<Setmeal>()
                .eq(categoryId != null, Setmeal::getCategoryId, categoryId)
                .eq(status != null, Setmeal::getStatus, status)
                .like(StrUtil.isNotBlank(name), Setmeal::getName, name);

        page(page, wrapper);
        return new PageResult(page.getTotal(),page.getRecords());

    }

    /**
     * 批量删除套餐
     * @param ids
     */
    @Override
    @GlobalTransactional
    public void deleteBatch(List<Long> ids) {
        List<Setmeal> setmeals = listByIds(ids);
        for (Setmeal setmeal : setmeals) {
            if(StatusConstant.ENABLE == setmeal.getStatus()){
                //起售中的套餐不能删除
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        }

        removeBatchByIds(ids);
        setMealDishService.remove(new LambdaQueryWrapper<SetmealDish>()
                .in(SetmealDish::getSetmealId, ids));
    }

    /**
     * 根据id查询套餐
     * @param id
     * @return
     */
    @Override
    public SetmealVO getByIdWithDish(Long id) {
        SetmealVO setmealVO = setMealMapper.getByIdWithDish(id);
        return setmealVO;
    }

    /**
     * 修改套餐
     * @param setmealDTO
     */
    @Override
    @GlobalTransactional
    public void update(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO,setmeal);

        //修改套餐表
        updateById(setmeal);

        Long id = setmealDTO.getId();
        //删除套餐和菜品的关联关系
        setMealDishService.remove(new LambdaQueryWrapper<SetmealDish>()
                .eq(SetmealDish::getSetmealId, id));
        //重新插入关联关系
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();
        setmealDishes.forEach(setmealDish -> {
            setmealDish.setSetmealId(id);
        });

        //插入数据到关联表
        setMealDishService.saveBatch(setmealDishes);

    }

    /**
     * 套餐起售停售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        //启售套餐，检测套餐内是否存在未启售菜品
        if (StatusConstant.ENABLE == status){
            List<Long> dishIds = setMealDishService.lambdaQuery()
                    .eq(SetmealDish::getSetmealId, id)
                    .list()
                    .stream().map(SetmealDish::getDishId).collect(Collectors.toList());
            List<Dish> dishes = Db.lambdaQuery(Dish.class)
                    .in(Dish::getId, dishIds)
                    .list();
            dishes.forEach(dish -> {
                if (StatusConstant.DISABLE == dish.getStatus()){
                    throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                }
            });
        }

        //组装
        Setmeal setmeal = Setmeal.builder()
                .id(id)
                .status(status)
                .build();

        updateById(setmeal);
    }

    @Override
    public List<Setmeal> list(Setmeal setmeal) {
        String name = setmeal.getName();
        Long categoryId = setmeal.getCategoryId();
        Integer status = setmeal.getStatus();
        return lambdaQuery()
                .like(StringUtils.isNotBlank(name), Setmeal::getName, name)
                .eq(categoryId != null, Setmeal::getCategoryId, categoryId)
                .eq(status != null, Setmeal::getStatus, status)
                .list();
    }

    @Override
    public List<DishItemVO> getDishItemById(Long id) {
        return setMealMapper.getDishItemBySetmealId(id);
    }
}
